<script lang="ts" setup>
  import { useDrag } from 'vue3-dnd'
  import { computed, unref } from 'vue'
  import { toRefs } from '@vueuse/core'

  interface DropResult {
    name: string
    id: string
  }

  const props = defineProps<{
    dragItem: DropResult
    isRepeat: (dragId: string) => any,
  }>()

  const [collect, drag] = useDrag(() => ({
    type: "itemBox",
    // 拖拽目标的数据
    item: () => ({
      name: props.dragItem.name,
      id: props.dragItem.id
    }),
    // 拖拽结束触发
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult<DropResult>()
      console.log("end-item", item)
      console.log('dropResult', dropResult)

      if (item && dropResult && props.isRepeat(item.id)) {
        alert(`不能重复放置${item.name}`)
        return
      }
      if (item && dropResult) {
        emit("changeList", item.id, dropResult.dropId)
      }
    },
    // collect的数据会挂载到collect参数上
    collect: monitor => ({
      isDragging: monitor.isDragging()
    }),
  }))

  const { isDragging } = toRefs(collect)
  const opacity = computed(() => (unref(isDragging) ? 0.4 : 1))

  const emit = defineEmits<{
    (e: 'changeList', dragId: string, dropId: string): void
  }>()
</script>

<template>
  <div
    class="dragBox"
    :ref="drag"
    :style="{ opacity }"
  >
    {{ props.dragItem.name }}
  </div>
</template>

<style lang="scss" scoped>
  .dragBox {
    border: 1px solid blue;
    padding: 20px;
    cursor: move;
  }
</style>